package com.xiangxiangjd.config.springsecurity;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiangxiangjd.bean.TrUser;
import com.xiangxiangjd.service.TrUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 根据用户名获取数据库该用户信息，spring security在登录时自动调用
 * WebSecurityConfigurerAdapter会拿这里的User里的password与用户输入的对比验证
 * GYB
 * 20190219
 */
@Service
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    TrUserService trUserService;




    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("username : "+username);


        //更具账号查询 数据账号 密码进行校验
        TrUser user = trUserService.getOne(new LambdaQueryWrapper<TrUser>().eq(TrUser::getUserName, username));


//        if (user == null) {
//            System.out.println("用户不存在：" + username);
//            throw new UsernameNotFoundException(String.format("用户名不存在"));
//        }

        System.out.println("用户的角色为："+user.getUserAdmin());


        //查询角色权限
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        if (user.getUserAdmin()==0) {

            GrantedAuthority a = new SimpleGrantedAuthority("ROLE_USER");
            list.add(a);

        } else if (user.getUserAdmin()==1) {


            GrantedAuthority a = new SimpleGrantedAuthority("ROLE_USER");
            GrantedAuthority b = new SimpleGrantedAuthority("ROLE_ADMIN");
            list.add(a);
            list.add(b);
        } else {

            GrantedAuthority a = new SimpleGrantedAuthority("ROLE_USER");
            GrantedAuthority b = new SimpleGrantedAuthority("ROLE_ADMIN");
            GrantedAuthority c = new SimpleGrantedAuthority("ROLE_SUPER_ADMIN");
            list.add(a);
            list.add(b);
            list.add(c);
        }


        String password = MD5Util.string2MD5(user.getPassWord());


        //123456 自定义MD5加密后=e10adc3949ba59abbe56e057f20f883e
        JwtUser JwtUser = new JwtUser(username, password, list);

        if (JwtUser == null) {
            throw new UsernameNotFoundException(String.format("No user found with username."));
        }
        System.out.println(JwtUser);
        return JwtUser;
    }

    public static void main(String[] args) {
//        MD5Util.convertMD5()


    }


}
